(function() {
	// 准备工作
	function prepare() {
		const imgTask = (img, src) => {
			return new Promise(function(resolve, reject) {
				img.onload = resolve;
				img.onerror = reject;
				img.src = src;
			});
		};

		const context = document.getElementById('content').getContext('2d');
		const heroImg = new Image();
		const allSpriteImg = new Image();
		var direction = "";
		const allresourceTask = Promise.all([
			imgTask(heroImg, './hero.png'),
			imgTask(allSpriteImg, './all.jpg'),
		]);

		return {
			/**
			 * @param {Function} [callback] - 当准备好了之后要调用的回掉函数
			 */
			getResource(callback) {
				allresourceTask.then(function() {
					callback && callback(context, direction, heroImg, allSpriteImg);
				});
			}
		};
	}

	// 画图
	function drawCharacter(context, direction, heroImg, allSpriteImg) {

		function Character() {
			this.img = heroImg;
			this.context = context;
		}

		Character.prototype.imgPos = {
			x: 0,
			y: 0,
			width: 32,
			height: 32
		};
		Character.prototype.rect = {
			x: 32,
			y: 32,
			width: 40,
			height: 40
		};

		Character.prototype.drow = function() {
			this.context.drawImage(
				this.img,
				this.imgPos.x,
				this.imgPos.y,
				this.imgPos.width,
				this.imgPos.height,
				this.rect.x,
				this.rect.y,
				this.rect.width,
				this.rect.height
			);
		}
		
		
		var a = new Character();
		
		
		if (direction == "down") {
			a.__proto__.rect.y-= 10;
		} else if (direction == "up") {
			a.rect.y += 10;
		} else if (direction == "left") {
			a.rect.x -= 10;
		} else if (direction == "right") {
			a.rect.x += 10;
		}
		console.log(a.rect)
		a.drow();
	}

	var resourceManager = prepare();
	resourceManager.getResource(function(context, direction, heroImg, allSpriteImg) {
		drawCharacter(context, "down", heroImg, allSpriteImg);
	});

	document.onkeydown = function(event) {
		var e = event || window.event || arguments.callee.caller.arguments[0];
		if (e && e.keyCode == 38) { //上 
			resourceManager.getResource(function(context, direction, heroImg, allSpriteImg) {
				drawCharacter(context, 'up', heroImg, allSpriteImg);
			});
		}
		if (e && e.keyCode == 40) { //下 
			resourceManager.getResource(function(context, direction, heroImg, allSpriteImg) {
				drawCharacter(context, 'down', heroImg, allSpriteImg);
			});
		}
		if (e && e.keyCode == 37) { //左
			resourceManager.getResource(function(context, direction, heroImg, allSpriteImg) {
				drawCharacter(context, 'left', heroImg, allSpriteImg);
			});
		}
		if (e && e.keyCode == 39) { //右
			resourceManager.getResource(function(context, direction, heroImg, allSpriteImg) {
				drawCharacter(context, 'right', heroImg, allSpriteImg);
			});
		}
	}

})();
